<template>
  <el-drawer 
    v-model="visible" 
    :title="`用电记录 (${meterName || '--'})`" 
    size="350px" 
    append-to-body 
    lock-scroll
  >
    <el-tabs
      v-model="type"
      type="card"
      @tab-change="handleTabChange"
    >
      <el-tab-pane label="年" name="year" />
      <el-tab-pane label="月" name="month" />
      <el-tab-pane label="日" name="day" />
    </el-tabs>
    <DateType 
      :type="type" 
      :loading="loading"
      :list="list"
      @date-change="handleDateChange"
    />
  </el-drawer>
</template>

<script setup>
import { getRecordList } from '@/api/device/eleMeter'
import DateType from './dateType.vue'

const props = defineProps({
  electricityMeterId: {
    type: [String, Number],
    required: true
  },
  meterName: {
    type: String,
    default: ''
  }
})

defineExpose({
  show
})

const visible = ref(false)
const type = ref('day') // 改为默认显示日视图
const loading = ref(false)
const list = ref([])

// 监听显示状态
watch(() => visible.value, value => {
  if (value) {
    // 打开时默认查询当日数据
    const today = new Date().toISOString().split('T')[0]
    getList(today, today)
  }
})

/* tabs切换 */
function handleTabChange(active) {
  type.value = active
  
  // 切换时重置为当前时间段
  const now = new Date()
  let startDate, endDate
  
  switch(active) {
    case 'year':
      startDate = `${now.getFullYear()}-01-01`
      endDate = `${now.getFullYear()}-12-31`
      break
    case 'month':
      const year = now.getFullYear()
      const month = now.getMonth() + 1
      const lastDay = new Date(year, month, 0).getDate()
      startDate = `${year}-${month.toString().padStart(2, '0')}-01`
      endDate = `${year}-${month.toString().padStart(2, '0')}-${lastDay}`
      break
    case 'day':
    default:
      const today = now.toISOString().split('T')[0]
      startDate = today
      endDate = today
      break
  }
  
  getList(startDate, endDate)
}

/* 日期变化 */
function handleDateChange({ startDate, endDate }) {
  getList(startDate, endDate)
}

/* 获取用电记录 */
function getList(startDate, endDate) {
  loading.value = true
  getRecordList(props.electricityMeterId, {
    startDate,
    endDate,
    dateType: type.value
  }).then(res => {
    list.value = res.rows || []
  }).finally(() => {
    loading.value = false
  })
}

function show() {
  visible.value = true
}
</script>
